package com.qianchang.microfinance.view.mine;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.PhoneUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.utils.ViewUtils;
import com.dm.library.widgets.CircleImageView;
import com.dm.library.widgets.DampScrollView;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.view.credit.data.ConfirmInfoJinbaoActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;
import com.qianchang.microfinance.view.home.cash.ApplyCashActivity;
import com.qianchang.microfinance.view.hscustomerservice.CustomerServiceActivity;
import com.qianchang.microfinance.view.hsmywallet.HSMyWallterActivity;
import com.qianchang.microfinance.view.hsmywallet.HSRecharCentreActivity;
import com.qianchang.microfinance.view.hsrecharge.HSReChargeActivity;
import com.qianchang.microfinance.view.login.LoginActivity;
import com.qianchang.microfinance.view.membercentre.MemberCentreActivity;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.view.CropImageView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.MineUserInfo;
import com.qianchang.microfinance.bean.UploadFileBean;
import com.qianchang.microfinance.bean.event.LoginEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.setting.SettingActivity;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.GlideImageLoader;
import com.qianchang.microfinance.view.base.DmBaseActivity;
import com.qianchang.microfinance.view.credit.data.BankCardDetailActivity;
import com.qianchang.microfinance.view.credit.data.BindBankCardActivity;
import com.qianchang.microfinance.view.credit.data.ScanIdentityActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengConfirmAlertDialog;
import com.qianchang.microfinance.view.manager.ImageChoseFragment;
import com.qianchang.microfinance.view.mine.bill.MyBillActivity;
import com.qianchang.microfinance.view.mine.intention.LoanIntentionActivity;
import com.qianchang.microfinance.view.mine.loan.MyLoanActivity;
import com.qianchang.microfinance.view.mine.renewal.RenewalActivity;
import com.qianchang.microfinance.view.tlpay.TlPayInputActivity;
import com.qianchang.microfinance.widgets.loadview.XLoadingView;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <描述>
 * 修 改 人: sushuo
 * 修改时间: 2017-5-26
 */

public class MineFragment extends ImageChoseFragment implements SwipeRefreshLayout.OnRefreshListener, ImageChoseFragment.UpLoadFileCallback {

    private static final String TAG = "MineFragment";
    Unbinder unbinder;

    private static MineFragment instance;
    @BindView(R.id.iv_head_img)
    CircleImageView ivHeadImg;
    @BindView(R.id.left_head_img)
    CircleImageView ivLeftHeadImg;              //2017.12.14 鸿胜科技新增
    @BindView(R.id.tv_title_left_id)
    DTextView tvPhoneNub;                       //2017.12.14 鸿胜科技新增
    @BindView(R.id.tv_user_name)
    DTextView tvUserName;
    @BindView(R.id.tv_score)
    DTextView tvScore;
    @BindView(R.id.tv_score_note_id)                //2017.12.14 鸿胜科技新增
    DTextView tvScoreNoet;
    @BindView(R.id.tv_borrowLines)
    DTextView tvBorrowLines;
    @BindView(R.id.tv_firstApplyAmount)
    DTextView tvFirstApplyAmount;
    @BindView(R.id.ll_my_bill)
    OneLineLinearLayout llMyBill;
    @BindView(R.id.ll_my_wallet)
    OneLineLinearLayout llMyWallet;
    @BindView(R.id.ll_my_loan)
    OneLineLinearLayout llMyLoan;
    @BindView(R.id.ll_loan_intention)
    OneLineLinearLayout llLoanIntention;
    @BindView(R.id.ll_identity_authentication)
    OneLineLinearLayout llIdentityAuthentication;
    @BindView(R.id.ll_bank_account)
    OneLineLinearLayout llBankAccount;
    @BindView(R.id.content)
    DampScrollView content;
    @BindView(R.id.ll_membercentre_id)
    OneLineLinearLayout membercentreLinear;
    @BindView(R.id.ll_user_suppl)
    OneLineLinearLayout userSuupl;

    @BindView(R.id.load_mine)
    XLoadingView loadMine;
    @BindView(R.id.tv_account_id)
    DTextView balance;
    private MineUserInfo mineUserInfo;
    private FindUserBasicInfoBean basicInfoBean = new FindUserBasicInfoBean();
    private JsonResult<FindUserBasicInfoBean> mResponse;
    private double rechangeAmount = 0.01;
    public static MineFragment getInstance() {
        if (null == instance) {
            synchronized (MineFragment.class) {
                if (null == instance) {
                    instance = new MineFragment();
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected View onRootViewCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mRootView = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, mRootView);
        if (ConstantAppInfo.IS_ONLY_CASH) {
            llLoanIntention.setVisibility(View.GONE);
//            llLoanIntention.setVisibility(View.VISIBLE);        //2017.12.14 鸿胜科技新增
        } else {
            llLoanIntention.setVisibility(View.VISIBLE);
        }
        return mRootView;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("");

//        setLeftContent(null, R.drawable.btn_sz);          //2017.12.14 鸿胜科技注释迪蒙原来的代码

        setLeftLineaVisible();                              //2017.12.14 鸿胜科技新增 头像
        setRightContent(null, R.drawable.btn_xx);           //消息图标
        setRightTwoContent(null,R.drawable.btn_sz);        //2017.12.14 鸿胜科技新增 设置图标
        setMaxImageCount(1);        //图片选择相关
        setUpLoadCallBackListener(this);    //设置上传回调
        //重试/刷新用户信息用
        loadMine.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getUserInfo();
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        //获取用户信息
        getUserInfo();
        //获取最新状态
        updateStatus();
    }


    //获取用户信息
    public void getUserInfo() {
        ((DmBaseActivity) mContext).show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_USER_INFO, params, new RequestCallBack<MineUserInfo>() {
            @Override
            public void onSuccess(JsonResult<MineUserInfo> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    mineUserInfo = response.getObject();
                    if (null != mineUserInfo) {
                        //获取完后刷新UI
                        refreshUi(mineUserInfo);
                        //loadMine控件中显示相应内容
                        loadMine.showContent();
                    }
                } else {
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(mContext, response.getDescription());
                        }
                    } else {
//                        DMApplication.getInstance().setUserLoginInfo(null);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(mContext, msg);
                if(loadMine != null)
                  loadMine.showError();
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    /**
     * 退出登录
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Logout(LoginEvent loginEvent) {
        LoginEvent.LoginStatue loginState = loginEvent.getLoginState();
        switch (loginState) {
            case LOGIN_SUC:
                getUserInfo();
                break;
        }
    }

    /**
     * 刷新UI
     * @param mineUserInfo
     */
    private void refreshUi(MineUserInfo mineUserInfo) {
        if (null != mineUserInfo) {
            tvUserName.setTextContent(ViewUtils.formatPhone(mineUserInfo.getPhone()));              //2017.12.14 注释迪蒙的
            tvPhoneNub.setTextContent(ViewUtils.formatPhone(mineUserInfo.getPhone()));              //2017.12.14 鸿胜科技新增自己的
//            tvScore.setTextContent(mContext.getString(R.string.label_total_amount) + FormatUtil.numKbPointFormat(mineUserInfo.getLoanLimit()));  //总额度          //2017.12.14 鸿胜注释
            tvScore.setTextContent(FormatUtil.numKbPointFormat(mineUserInfo.getBorrowLimit()));  //可用额度    2017.12.14 新增自己的
            tvScoreNoet.setText(mContext.getString(R.string.label_keyong_amount) + "(元)");               // 2017.12.14 新增自己的
            balance.setText(FormatUtil.numKbPointFormat(mineUserInfo.getBalance()));
            tvBorrowLines.setTextContent(FormatUtil.numKbPointFormat(mineUserInfo.getStayAmount()));//待还金额
            tvFirstApplyAmount.setTextContent(FormatUtil.numKbPointFormat(mineUserInfo.getRepaidAmount()));//已还金额
//            llMyWallet.setRightContent(FormatUtil.numKbPointFormat(mineUserInfo.getAvailable()));   //可用余额  （钱包余额？）
            llMyWallet.setRightContent(FormatUtil.numKbPointFormat(mineUserInfo.getBalance()));   //可用余额  （钱包余额？）
            Glide.with(mContext).load(DMConstant.Config.BASE_URL + mineUserInfo.getImageUrl()).error(R.drawable.btn_mrtx).into(ivHeadImg);          //2017.12.14 注释掉迪蒙的代码
            Glide.with(mContext).load(DMConstant.Config.BASE_URL + mineUserInfo.getImageUrl()).error(R.drawable.btn_mrtx).into(ivLeftHeadImg);          //2017.12.14 鸿胜科技新增自己需要的代码
        }
    }

    @OnClick({R.id.iv_head_img,R.id.left_head_img, R.id.ll_my_bill, R.id.ll_my_wallet, R.id.ll_my_loan,
            R.id.ll_loan_intention, R.id.ll_identity_authentication, R.id.ll_bank_account, R.id.tv_back,
            R.id.tv_right,R.id.tv_right_two,R.id.tv_membercentre_money_id,R.id.tv_recharge_centre_id,
            R.id.tv_repayment_money_id,R.id.ll_membercentre_id,R.id.tv_customer_service_id,R.id.tv_online_service_id,R.id.ll_user_suppl,R.id.ll_Renewal_id})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(MineUserInfo.class.getName(), mineUserInfo);
        bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
        switch (view.getId()) {
            case R.id.iv_head_img:
                showSelectPhotoDialog();            //2017.12.14 鸿胜科技注释掉迪蒙原来代码 摈弃不用
                break;
            case R.id.left_head_img:           //2017.12.14 鸿胜新增自己的
                showSelectPhotoDialog();        //选择头像
                break;
            case R.id.tv_recharge_centre_id:                           //跳转充值中心             2018.1.16鸿盛新增
                //startActivity(HSRecharCentreActivity.class);

                startActivity(RechargeFixActivity.class);
                break;
            case R.id.tv_repayment_money_id:                            //还款管理
                startActivity(MyBillActivity.class);
                break;
            case R.id.tv_membercentre_money_id:                     //跳转会员中心            2017.12.28鸿盛新增
                startActivity(MemberCentreActivity.class);
//                ToastUtil.getInstant().show(getActivity(),"待开发");
                break;
            case R.id.ll_my_bill:                                       //我的账单
                startActivity(MyBillActivity.class);
                break;
            case R.id.ll_my_wallet:     //我的钱包

//                startActivity(MyWalletActivity.class, bundle);              //2018.1.16   注释迪蒙代码

                startActivity(HSMyWallterActivity.class, bundle);               //跳转我的钱包

                break;
            case R.id.ll_my_loan:                               //我的借款
                startActivity(MyLoanActivity.class);
                break;
            case R.id.ll_Renewal_id:                    //一键续贷
                startActivity(RenewalActivity.class);
                break;
            case R.id.ll_loan_intention://借款意图
                startActivity(LoanIntentionActivity.class);
                break;
            case R.id.tv_back:      //这个好像没用到
                startActivity(SettingActivity.class);
                break;
            case R.id.tv_right: //跳转至我的消息
                startActivity(MessageListActivity.class);                   //2017.12.14鸿胜科技把左边设置移动到右边后注释掉原来的
                break;
            case R.id.tv_right_two: //跳转至设置                         //2017.12.14鸿胜科技新增把设置从左边移动到右边
                startActivity(SettingActivity.class);
                break;
            case R.id.ll_identity_authentication://身份认证  实名认证
                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                startActivity(ScanIdentityActivity.class, bundle);
                break;
            case R.id.ll_membercentre_id:       //认证中心
//                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                bundle.putString(ConstantAppInfo.PROJECT_TYPE, LoanType.JBD);
                startActivity(ConfirmInfoJinbaoActivity.class, bundle);

                break;
            case R.id.ll_user_suppl:       //我的借款资料
                startActivity(UserSupplActivity.class, bundle);

                break;
            case R.id.tv_customer_service_id:           //客服电话
                call(getString(R.string.service_line));
                break;
            case R.id.tv_online_service_id:             //在线客服
                startActivity(CustomerServiceActivity.class);
                break;
            default:
                clickNeedIdentify(view, bundle);                //我的银行卡
                break;
        }
    }

    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }


    /**
     * 点击校验实名认证
     */
    private void clickNeedIdentify(View view, Bundle bundle) {
        switch (view.getId()) {
            case R.id.ll_bank_account://我的银行账号
                toBindBankCard(bundle);
                break;
        }
    }

    private void updateStatus() {
        show();
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {
            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                dismiss();
                mResponse = response;
                Log.i(TAG, response.toString());
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    basicInfoBean = response.getObject();
                    if (basicInfoBean == null){
                        basicInfoBean = new FindUserBasicInfoBean();
                    }
                } else {
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(mContext, response.getDescription());
                        }
                    } else {
                        DMApplication.getInstance().setUserLoginInfo(null);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }

        });
    }

    private void toBindBankCard(final Bundle bundle) {

        /**** 2018.1.19 鸿胜科技占时注释掉代码
        if (basicInfoBean.getIsIdCardCheckThrough() == 0) {//未进行实名认证，点击人脸识别、银行卡信息，提示“请先完成实名认证”；
            if (0 == basicInfoBean.getIsBankCardBind()) {//是否添加银行卡绑定，0：是、1：否
                startActivity(BankCardDetailActivity.class, bundle);
            } else {
                startActivity(BindBankCardActivity.class, bundle);
            }
        } else {
            DimengConfirmAlertDialog confirmAlertDialog = DimengConfirmAlertDialog.newInstance("", getString(R.string.please_identify_first));
            confirmAlertDialog.setOnDialogClickListener(new DimengConfirmAlertDialog.OnDialogClickListener() {
                @Override
                public void agree() {
                    startActivity(ScanIdentityActivity.class, bundle);
                }

                @Override
                public void cancel() {
                }
            });
            confirmAlertDialog.setAgreeText(getString(R.string.go_certified));
            confirmAlertDialog.show(getFragmentManager(), getClass().getSimpleName());
        }
         ****/

        //2018.1.19鸿胜科技新增

        if(basicInfoBean != null){
            if (0 != basicInfoBean.getIsIdCardCheckThrough()) {
                ToastUtil.getInstant().show(getContext(), getString(R.string.msg_shoild_submit_IdCardCheck));
                return;
            }
        }else{
            ToastUtil.getInstant().show(getContext(), "数据异常");
            return;
        }
        startActivity(BankCardDetailActivity.class, bundle);
    }


    @Override
    public void onPhotoResult(ArrayList<ImageItem> imageItems, int flag) {
        if (null != imageItems && imageItems.size() > 0) {
            String filePath = imageItems.get(0).path;
            uploadFile(filePath);
            clearSelectImages();
        }
    }


    //fragment显示状态每变化一次刷新一次用户数据？
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getUserInfo();
            updateStatus();
        }
    }

    //每onResume一次刷新一次用户数据？
    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        updateStatus();
        MobclickAgent.onPageStart("MineFragment");         //友盟统计 Fragment  页面统计
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MineFragment");       //友盟统计 Fragment  页面统计
    }

    //每刷新一次则获取一次用户数据
    @Override
    public void onRefresh() {
        getUserInfo();
        updateStatus();
    }

    //上传头像成功
    @Override
    public void onUpLoadSuccess(UploadFileBean uploadFileBean, String imagePath, int flag) {
        if (null != uploadFileBean) {
            String imageUrl = uploadFileBean.getUrl();
            //更新用户头像
            updateUserPhoto(imageUrl, imagePath);
        }
    }

    //提交上传的头像url
    private void updateUserPhoto(final String imageUrl, final String imagePath) {
        HttpParams params = new HttpParams();
        params.put("imageUrl", imageUrl);
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.UPDATE_USER_PHOTO, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    Glide.with(mContext).load(imagePath).error(R.drawable.img_swed).into(ivHeadImg);                //2017.12.14 注释掉迪蒙的
                    Glide.with(mContext).load(imagePath).error(R.drawable.img_swed).into(ivLeftHeadImg);                //2017.12.14 鸿胜科技新增自己的
                } else {
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(mContext, response.getDescription());
                        }
                    } else {
                        DMApplication.getInstance().setUserLoginInfo(null);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    /**
     * 设置选择图片的ImagePicker配置
     *
     * @param selectedImageSize 已选择图片数量
     */
    @Override
    public void initImagePickerForSelectPhoto(int selectedImageSize) {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(false);//单选多选
        imagePicker.setSelectLimit(maxImgCount - selectedImageSize);
        imagePicker.setShowCamera(false);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setFocusWidth(PhoneUtil.getPhoneWidth((Activity) mContext)); //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(PhoneUtil.getPhoneWidth((Activity) mContext)); //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        ImagePicker.getInstance().setOutPutX(PhoneUtil.dip2px(mContext, 70));//70：xml中view设置的宽度dp值  保存文件的宽度。单位像素
        ImagePicker.getInstance().setOutPutY(PhoneUtil.dip2px(mContext, 70));//保存文件的高度。单位像素
    }

    /**
     * 设置拍照的ImagePicker配置
     */
    @Override
    public void initImagePickerForTakePhoto() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(false);//单选多选
        imagePicker.setSelectLimit(1);
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(false);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(PhoneUtil.getPhoneWidth((Activity) mContext)); //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(PhoneUtil.getPhoneWidth((Activity) mContext)); //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        ImagePicker.getInstance().setOutPutX(PhoneUtil.dip2px(mContext, 70));//70：xml中view设置的宽度dp值  保存文件的宽度。单位像素
        ImagePicker.getInstance().setOutPutY(PhoneUtil.dip2px(mContext, 70));//保存文件的高度。单位像素
    }


    //客服电话
    private void dial() {
        String phone = "";
        phone = getString(R.string.service_line);
        if (TextUtils.isEmpty(phone)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        startActivity(intent);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }


}
